package com.caiheng.api.controller.estate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.*;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.*;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.wxuser.UserService;
import com.vdurmont.emoji.EmojiParser;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  物业接待日相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/estate/chat")//url:模块/资源/{}/细分
public class EstateChatController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private EstateChatService estateChatService;
    @Resource
    private EstateChatApplyService estateChatApplyService;
    @Resource
    private EstateService estateService;
    @Resource
    private EstateChatImgService chatImgService;
    @Resource
    private WxTemplateService wxTemplateService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.appid}")
    private String appid;
    @Value("${web.secret}")
    private String secret;

    /**
     * 发起对讲
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add")
    public JSONObject add(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            if(StrUtil.isEmpty(content)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"内容不能为空"),true,true);
            }

            EstateChat chat = new EstateChat();
            chat.setUserId(user_id);
            chat.setContent(content);
            chat.setCreateTime(new Date());
            chat.setEstateId(user.getEstateId());
            chat.setState(0);

            Estate estate = estateService.findById(user.getEstateId());
            if(estate!=null){
                chat.setEstateName(estate.getEstateName());
            }

            boolean bl = estateChatService.save(chat);
            if(bl){
                //发推送消息
                wxTemplateService.sendWxMsgEstateChatToManager(chat);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功",chat.getId()),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int chat_id = jsonRequest.containsKey("chat_id") ? jsonRequest.getInt("chat_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            EstateChat chat = estateChatService.getChatById(chat_id);
            if(chat == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该内容不存在"),true,true);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("chat",chat);


            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nickName", EmojiParser.parseToUnicode(user.getNickName()));
            }
            map.put("faceUrl",user.getFaceUrl());




            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  我的列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            List<EstateChat> chats = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            EstateUser estateUser = estateUserService.getEstateUser(user_id);
            if(estateUser != null){
                chats = estateChatService.getListByEstateId(estateUser.getEstateId(),state,pageIndex,pageSize);
            }else{
                chats = estateChatService.getListByUserId(user_id,pageIndex,pageSize);
            }
            map.put("chats",chats);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",chats.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  回复
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/apply")
    public JSONObject addApply(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int chat_id = jsonRequest.containsKey("chat_id") ? jsonRequest.getInt("chat_id") : 0;
            String apply_id = jsonRequest.containsKey("apply_id") ? jsonRequest.getStr("apply_id") : "";
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定社区"),true,true);
            }

            EstateChat chat = estateChatService.findById(chat_id);
            if(chat == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"对话不存在"),true,true);
            }

            if(StrUtil.isEmpty(content)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"内容不能为空"),true,true);
            }

            boolean blValidate = Tools.isSqlValid(content);
            if(!blValidate){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "存在违禁词，修改后再输入"), true, true);
            }

            // 校验发布内容是否违规
            boolean checkContent = WxMessage.checkContent(user.getOpenId(), content, appid, secret);
            if (checkContent) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "发布的内容涉嫌违规，请重新修改后再发布"), true, true);
            }

            Map<String,Object> map = new HashMap<>();
            String applyId = estateChatApplyService.addApply(user,chat,apply_id,content);
            if(StrUtil.isNotEmpty(applyId)){
                List<EstateChatApply> estateChatApplies = estateChatApplyService.getListByChatId(chat_id);
                map.put("applies", estateChatApplies);
                map.put("applyId", applyId);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"提交成功",map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  上传图片
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(@RequestParam("chat_id") int chat_id,
                                @RequestParam("img_type") Integer img_type,
                                @RequestParam("sort") Integer sort, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("chat_id==" + chat_id);

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();

                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "common_info_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_ESTATE_CHAT;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() + "/" + fileName;

                                        String path = uploadPath + OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() ;
                                        System.out.println("path: " + path);
                                        File file = new File(path);
                                        if (!file.exists() && !file.isDirectory()) {
                                            file.mkdirs();
                                        }

                                        String filePath =  path +"/" + fileName;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();


                                        ImagesFiler.imageResize(filePath,filePath);

                                        OssUtil.uploadObs(certurl.getInputStream(),DateUtil.getSdfYearDay() + "/" + fileName,upload_type);

                                        EstateChatImg chatImg = new EstateChatImg();
                                        chatImg.setChatId(chat_id);
                                        chatImg.setImgType(img_type);
                                        chatImg.setSort(1);
                                        if(sort!=null){
                                            chatImg.setSort(sort);
                                        }
                                        chatImg.setImgUrl(img_key);
                                        chatImgService.save(chatImg);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }
}
